<?php 
class Modelstockfactory extends Model {
  public function getList($page = 1, $filter, $sort_data){
		$vblist = M('vendor_bill_new vb')
		->join('vendors vs on vs.vendor_id = vb.vendor_id','left')
		->order($sort_data['sort'] . ' ' . $sort_data['order'])
		->where($filter)->page($page)->limit($this->config->get('config_limit_admin'))->select();
		// var_dump(M()->getLastSql());die();
		return $vblist;
	}
	public function getAllList($filter, $sort_data){
		$vblist = M('vendor_bill_new vb')
		->join('vendors vs on vs.vendor_id = vb.vendor_id','left')
		->order($sort_data['sort'] . ' ' . $sort_data['order'])
		->where($filter)->select();
		// var_dump(M()->getLastSql());die();
		return $vblist;
	}
	public function getListCount($filter){
		$count = M('vendor_bill_new vb')->where($filter)->count();
		return $count;
	}

	public function getVendorBill($id){
		$vendor_bill = M('vendor_bill_new')->find($id);
		if($vendor_bill){
		  $vendor = M('vendors')->where('vendor_id='.$vendor_bill['vendor_id'])->find();
		  $vendor_bill['vendor_name'] = $vendor['vendor_name'];
		}
		return $vendor_bill;
	}

	public function getVendorBillPoCount($id){
		$where['vendor_bill_id'] = $id;
		$po = M('vendor_bill_money_out vbp')
		  ->where($where)
		  ->select();
		return $po;
	}

	public function getVendorBillPo($id){
		$where['vendor_bill_id'] = $id;
		$money_out = M('vendor_bill_money_out')
		  	->where($where)
		 	->select();
		foreach ($money_out as $key => $value) {
			$in_ids = M('money_out')->where(array('money_out_id'=>$value['money_out_id']))->field('stock_in_ids,refer_id')->find();
			$in_id_arr = explode(',',$in_ids['stock_in_ids'] );
			foreach ($in_id_arr as $key1 => $value1) {
				$product ='';
				if (!empty($value1)) {
				 $product = M('stock_in s')->where(array('s.in_id'=>(int)$value1))
					->join('stock_in_detail as sd on s.in_id = sd.in_id')
					->join('product_option_value as pv on pv.product_code = sd.product_code')
					->join('product_description as pd on pd.product_id = pv.product_id')
					->join('option_value_description as pds on pds.option_id = pv.option_id')
					->field('s.in_id,s.refer_id,s.in_date,sd.product_quantity,sd.product_price,sd.products_money,pd.name,pds.name as option_name')
					->group('sd.id')
					-> select();
				}
				foreach ($product as $key2 => $value2) {
					// var_dump($value);
					$c[]=$value2;
					// $pototal +=$value2['product_quantity']*$value2['product_price'];
				}
				
			}
			$pototal += M('po_product')->where(array('po_id'=>(int)$in_ids['refer_id']))
					-> getField('sum(unit_price*delivered_qty)');
			// echo  M('po_product')->getLastSql(); 
			
		}
		$c['pototal'] = $pototal;
		return $c;
	}

	public function getVendorBillHistories($id){
		$where['vendor_bill_id'] = $id;
		$vendor_bill_histories = M('vendor_bill_new_history')
		  ->where($where)
		  ->select();
		return $vendor_bill_histories;
	}

	public function getVendorByVendorBillId($id) {
		$where['vendor_bill_id'] = $id;
		$vb_info = M('vendor_bill_new vb')
		  ->where($where)
		  ->find();
		if(!empty($vb_info)) {
		  $query = M('vendors')->where(array('vendor_id'=>$vb_info['vendor_id']))->find();
		  return $query;
		}
		return null;
	}

	public function deleteBill($id) {
		$vendor_bill = M('vendor_bill_new');
		$vendor_bill->where(array('vendor_bill_id'=>$id))->delete();
		$mon_out = M('vendor_bill_money_out')->where(array('vendor_bill_id'=>$id))->select();
		foreach ($mon_out as $key => $value) {
			M('money_out')->where(array('money_out_id'=>$value['money_out_id']))->save(array('status'=>1));
		}
		$mon_out = M('vendor_bill_money_out')->where(array('vendor_bill_id'=>$id))->delete();
		// var_dump($mon_out);die();
	}

	public function getVendorIdsFromPo($orders) {
		$order_query = M('order_product op')
		->join('vendor v on v.vproduct_id=op.product_id')
		->where('op.order_id in (' . implode(',', $orders) . ')')
		->field('v.vendor as vendor_id')
		->group('v.vendor')
		->select();
		return $order_query;
	}

	public function setPoGeneratedFlag($orders) {
		foreach ($orders as $order_id) {
		  $Order = M('order');
		  $Order->where(array('order_id'=>$order_id))->setInc('po_generated');
	}
	}

	public function changeDifference($id, $difference) {
		$vendor_bill = M('vendor_bill_new');
		$vendor_bill->data(array('vendor_bill_id'=>$id, 'difference'=>$difference))->save();
	}

	public function changeVendorBillStatus($vendor_bill_id, $status) {
		$vendor_bill = M('vendor_bill_new');
		$vendor_bill->data(array('vendor_bill_id'=>$vendor_bill_id, 'status'=>$status))->save();
	}

	public function getBilledPo($cur_month, $end_month) {
		$map['year_month'] = array('between',array($end_month, $cur_month));
		// $map['date_added'] = array('between',array($end_month, $cur_month));
		// $map['vb.status'] = array('gt', 0);
		$query = M('vendor_bill_new vb')
		  ->join('vendor_bill_money_out vbp on vb.vendor_bill_id=vbp.vendor_bill_id')
		  ->where($map)
		  ->field('vbp.po_id')
		  ->select();
		return $query;
	}

	public function saveVendorBill($data, $po_ids) {
		$vendor_bill_id = M('vendor_bill_new')->add($data);
		foreach ($po_ids as $po_id) {
		  M('vendor_bill_money_out')->add(array('vendor_bill_id'=>$vendor_bill_id, 'po_id'=>$po_id));
		}
		return $vendor_bill_id;
	}

	public function addVendorBillHistory($vendor_bill_id, $user_id, $operator_name, $comment) {
		$vendorBillHistory = M('vendor_bill_history');
		$data = array('vendor_bill_id'=>$vendor_bill_id, 'user_id'=>$user_id, 
		  'operator_name'=>$operator_name, 'comment'=>$comment, 
		  'notify'=>0, 'date_added'=>date('Y-m-d H:i:s'));
		$vendorBillHistory->data($data)->add();
	}

	public function getVendors($vendor_id){
		$model = M('vendors');
		$field = array('vendor_id','vendor_name','bank_id','card_id','card_name');
		$query = $model->field($field)->find($vendor_id);
		return $query;
	}

    //创建支付条目
    public function addVBNP($data) {
        $sql = "INSERT INTO `vendor_bill_new_payment` SET ";
        foreach ($data as $col=>$val) {
            $sql .= "`".$col."`='".$this->db->escape($val)."',";
        }
        $this->db->query(substr($sql, 0, -1));
        return $this->db->getLastId();
    }

    //修改支付条目
    public function updateVBNP($pk, $data) {
        $temp = array();
        foreach ($data as $col=>$val) {
            $temp[] = "`".$col."`='".$this->db->escape($val)."'";
        }
        $sql = "UPDATE `vendor_bill_new_payment` SET ".implode(',', $temp)." WHERE `vendor_bill_new_payment_id`='".$pk."'";
        $this->db->query($sql);
    }

    //根据对账单编号，获取工厂收款信息
    public function getPaymentInfoByVBID($vbId) {
        $sql = "SELECT `vendor_name`,`iban_type`,`card_id`,`card_name`,`bank_id` FROM `vendors` WHERE vendor_id=(SELECT `vendor_id` FROM `vendor_bill_new` WHERE `vendor_bill_id`='".$vbId."')";
        $res = $this->db->query($sql);
        return $res->row;
    
    }

}

